import { computed } from "vue";
import { useStore } from "vuex";

//购物车逻辑
export const useCommonCartEffect = (shopId) => {
  const store = useStore();

  const { cartList } = store.state;

  const changeCartItemInfo = (shopId, productId, product, number) => {
    store.commit("addItemToCart", {
      shopId,
      productId,
      product,
      number,
    });
  };

  const productList = computed(() => {
    const productList = cartList[shopId]?.productList || {};
    const notEmptyProductList = {};
    for (let i in productList) {
      const product = productList[i];
      if (product.count > 0) {
        notEmptyProductList[i] = product;
      }
    }
    return notEmptyProductList;
  });

  const shopName = computed(() => {
    const shopName = cartList[shopId]?.shopName || "";
    return shopName;
  });

  const calculations = computed(() => {
    const productList = cartList[shopId]?.productList;

    const result = { totalCount: 0, totalPrice: 0, allChecked: true };
    for (let i in productList) {
      const product = productList[i];
      result.totalCount += product.count;
      if (product.check) {
        result.totalPrice += product.count * product.price;
      }
      if (product.count > 0 && !product.check) {
        result.allChecked = false;
      }
    }
    result.totalPrice = result.totalPrice.toFixed(2);
    return result;
  });

  return { changeCartItemInfo, cartList, productList, shopName, calculations };
};
